<template>
    <div style="display: flex;">
        <div style="flex: 1;">
            <el-input v-model="fillBlankText" placeholder="请输入填空的答案"
                style="width: 800px; margin-left: 120px; margin-top: 20px; margin-bottom: 20px;">
            </el-input>
            <el-button @click="addFillInTheBlankInput">+ 答案</el-button>
            <div>
                <div v-for="(input, index) in inputFields" :key="index" style="display: flex; align-items: center;">
                    <el-input v-model="input.value" placeholder="请输入答案"
                        style="width: 800px;margin-left: 120px;margin-bottom: 20px"></el-input>
                    <el-button style="margin-top: -20px;" @click="removeInputField(index)">删除</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { defineProps, ref, defineEmits, watchEffect, nextTick } from 'vue';

const props = defineProps({
    fillBlankAnswers: Array,
});

const emit = defineEmits(['update:fillBlankAnswers', 'addFillInTheBlankInput']);

// 用于管理动态输入框的状态
const inputFields = ref([]);

const fillBlankText = ref('');

const addFillInTheBlankInput = () => {
    // 在输入框数组中添加一个新的输入框
    inputFields.value.push({ value: fillBlankText.value });
    // 清空输入框
    fillBlankText.value = '';
    // 更新父组件中的状态
    emit('update:fillBlankAnswers', inputFields.value.map(field => field.value));
};

const removeInputField = (index) => {
    // 从输入框数组中移除指定索引的输入框
    inputFields.value.splice(index, 1);
    // 更新父组件中的状态
    emit('update:fillBlankAnswers', inputFields.value.map(field => field.value));
};

// 监听父组件传递的 fillBlankAnswers 变化
watchEffect(onInvalidate => {
    inputFields.value = props.fillBlankAnswers.map(answer => ({ value: answer }));
    onInvalidate(() => {
        emit('update:fillBlankAnswers', inputFields.value.map(field => field.value));
    });
});

// 避免无限循环更新
nextTick(() => {
    emit('update:fillBlankAnswers', inputFields.value.map(field => field.value));
});
</script>
<style scoped>
.radio-container {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.el-radio {
    margin-left: 0 !important;
}

/* 增加文本域的高度 */
.el-input__inner {
    height: auto;
}

/* 去掉无序列表的黑点 */
ul {
    list-style-type: none;
    padding-left: 0;
}
</style>